﻿using Shell.Build;

namespace Shell.Ioc
{
    class ConstructorAnalyst : IBuilder
    {
        public void PreBuild(IBuildContext context)
        {
            var plan = context.Policies.Get<IBuildPlan>(context.Identity);
            if (plan != null && plan.IsExecutable)
            {
                // (hanwen) if we got here, that means there we already have a ready plan to build, so here just don't do anything more
                return;
            }

            // (hanwen) if we got here, that means there we have a plan and it's not executable, so we replace the plan into our own
            var constructors = context.Identity.Type.GetConstructors();
            //TODO (hanwen) get the flaged constructor if more than one found.
            if (constructors.Length > 0)
            {
                var p = new IocBuildPlan(constructors[0]);
                p.Initialize(context);
                context.Policies.Set<IBuildPlan>(context.Identity, p);
            }
        }

        public void PostBuild(IBuildContext context)
        {
            var plan = context.Policies.Get<IocBuildPlan>(context.Identity);
            if (plan != null)
            {
                context.Policies.Remove<IocBuildPlan>(context.Identity);
            }
        }
    }
}
